<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert
        title="注意：只允许为第三级权限设置相关参数"
        type="warning"
        close-text="知道了"
        show-icon
      />
      <!-- 级联选择框 -->
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <!-- optionsy用来绑定数据源 -->
          <!-- props用来指定配置对象 -->
          <!--v-model 用来指定级联选择器选择的值-->
          <el-cascader
            v-model="paramsSelectKeys"
            :options="getCascaderList"
            :props="paramsProps"
            @change="paramsSelectChange"
            clearable
          />
        </el-col>
      </el-row>
      <!-- tabs区域 -->
      <el-tabs
        v-model="activeName"
        @tab-click="handleTabsClick"
      >
        <el-tab-pane
          label="动态参数"
          name="many"
        >
          <el-button
            type="primary"
            size="small"
            :disabled="isBtnDisabled"
            @click="addDialogVisible=true"
          >
            添加参数
          </el-button>
          <!-- 表格区域 -->
          <el-table
            :data="pramsManyData"
            style="width: 100%"
            border
            stripe
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="handleClosed(i,scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                />
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="#"
            />
            <el-table-column
              prop="attr_name"
              label="参数名称"
            />
            <el-table-column
              prop="attr_name"
              label="操作"
            >
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-edit"
                  type="primary"
                  size="mini"
                  @click="editParamsDialog(scope.row.attr_id)"
                >
                  编辑
                </el-button>
                <el-button
                  icon="el-icon-delete"
                  type="danger"
                  size="mini"
                  @click="editParamsDialogClosed(scope.row.attr_id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane
          label="静态属性"
          name="only"
        >
          <el-button
            type="primary"
            size="small"
            :disabled="isBtnDisabled"
            @click="addDialogVisible=true"
          >
            添加属性
          </el-button>
          <!-- 表格区域 -->
          <el-table
            :data="pramsOnlyData"
            style="width: 100%"
            border
            stripe
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                />
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="#"
            />
            <el-table-column
              prop="attr_name"
              label="属性名称"
            />
            <el-table-column
              prop="attr_name"
              label="操作"
            >
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-edit"
                  type="primary"
                  size="mini"
                  @click="editParamsDialog(scope.row.attr_id)"
                >
                  编辑
                </el-button>
                <el-button
                  icon="el-icon-delete"
                  type="danger"
                  size="mini"
                  @click="editParamsDialogClosed(scope.row.attr_id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加属性区域 -->
    <el-dialog
      :title="'添加' + isText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item
          :label="isText"
          prop="attr_name"
        >
          <el-input v-model="addForm.attr_name" />
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addParams"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改属性区域 -->
    <el-dialog
      :title="'修改' + isText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item
          :label="isText"
          prop="attr_name"
        >
          <el-input
            ref="inputRef"
            v-model="editForm.attr_name"
          />
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="editParams"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 获取级联选择器数据的需要发送请求的数据
      queryInfo: {
        type: 3
      },
      // 级联选择器数据
      getCascaderList: [],
      // 级联选择器当前所选择的数据
      paramsSelectKeys: [],
      // 级联选择器props的配置对象
      paramsProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 默认展示的tabs标签
      activeName: 'many',
      // 动态数据
      pramsManyData: [],
      // 静态数据
      pramsOnlyData: [],
      // 默认隐藏添加对话框
      addDialogVisible: false,
      editDialogVisible: false,
      // 定义表单
      addForm: {
        attr_name: ''
      },
      editForm: {},
      // 定义表单的校验规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' }
        ]
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 获取级联选择器数据
    this.getparamsSelectList()
  },
  methods: {
    // 获取级联选择器数据
    async getparamsSelectList() {
      const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.getCascaderList = res.data
      console.log(this.getCascaderList)
    },
    async getParamsData() {
      // paramsSelectKeys数组长度不等于3 选择的不是三级分类
      if (this.paramsSelectKeys.length !== 3) {
        this.paramsSelectKeys = []
        this.pramsManyData = []
        this.pramsOnlyData = []
      }
      // 请求分类表格的数据
      const { data: res } = await this.$http.get(`categories/${this.CateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('请选择具体分类')
      }
      // 循环res.data得到用split把字符串分割为数组并作判断返回数组或者空数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      // 根据请求 的 activeName 不同把res.data 放入不同的list里many 还是only
      if (this.activeName === 'many') {
        // 动态数据赋值
        this.pramsManyData = res.data
      } else {
        // 静态数据赋值
        this.pramsOnlyData = res.data
      }
    },
    // 级联选择器改变是执行
    paramsSelectChange() {
      this.getParamsData()
    },
    // 切换tabs标签触发
    handleTabsClick () {
      this.getParamsData()
      console.log(this.activeName)
    },
    // dialog关闭时触发
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 提交 添加的属性
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.CateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error('提交失败，请检查输入内容')
        }
        this.getParamsData()
        this.addDialogVisible = false
        this.$message.success(res.meta.msg)
      })
    },
    // 弹出编辑参数的对话框，操作
    async editParamsDialog(attrId) {
      // 根据id获取数据
      const { data: res } = await this.$http.get(`categories/${this.CateId}/attributes/${attrId}`, {
        attr_sel: this.activeName
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.editForm = res.data
      this.editDialogVisible = true
      // 获取自动获取input焦点focus
      this.$nextTick(_ => {
        this.$refs.inputRef.$refs.input.focus()
      })
    },
    // 提交编辑内容的对话框操作
    editParams() {
      // 表单验证
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.CateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name, attr_sel: this.editForm.attr_sel
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        this.getParamsData()
        this.editDialogVisible = false
        this.$message.success(res.meta.msg)
      })
    },
    // 删除属性数据的操作
    async editParamsDialogClosed(attrId) {
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(`categories/${this.CateId}/attributes/${attrId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.getParamsData()
      this.$message.success(res.meta.msg)
    },
    // 鼠标enter或者失去焦点blur时触发
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 满足条件后续处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发请求操作服务器数据
      this.saveAttrVals(row)
    },
    // Tag的添加和删除操作
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(`categories/${this.CateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('添加失败')
      }
      this.$message.success('更新成功')
    },
    // tag关闭事件
    handleClosed(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    },
    // 点击tag标签的按钮
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  computed: {
    // 控制 btn的隐藏和显示
    isBtnDisabled() {
      if (this.paramsSelectKeys.length !== 3) {
        return true
      }
      return false
    },
    // 获取到请求参数列表所需的分类id
    CateId() {
      if (this.paramsSelectKeys.length === 3) {
        return this.paramsSelectKeys[2]
      }
      return null
    },
    // 动态改变添加动态属性还是静态属性名称
    isText() {
      if (this.activeName === 'many') {
        return '动态属性'
      }
      return '静态属性'
    }
  }
}
</script>
<style lang="less" scoped>
.el-row{margin: 15px 0;}
.el-tag{margin: 5px 15px;}
.input-new-tag{width: 150px;}
</style>
